package cn.ztydata.teachingsystem.heaven.entity.oxm;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 权限信息类
 * Created by chenxin on 2015/02/28.
 */
@XStreamAlias("root")
public class PrivilegeInfo {
    private static Logger log = LoggerFactory.getLogger(PrivilegeInfo.class); //日志记录器

    @XStreamAlias("get")
    private Method methodGet;
    @XStreamAlias("post")
    private Method methodPost;
    @XStreamAlias("put")
    private Method methodPut;
    @XStreamAlias("delete")
    private Method methodDelete;

    /**
     * 判断权限是否有效
     * @param method 请求方式
     * @param privilege 请求权限
     * @return boolean
     *
     * @author cx
     * @since 2015-02-28
     */
    public boolean judgePrivilege(final String method, final String privilege) {
        switch(method) {
            case "GET" :
                log.debug("method:GET");
                return hasPrivilege(methodGet.getUrl(), privilege);
            case "POST" :
                log.debug("method:POST");
                return hasPrivilege(methodPost.getUrl(), privilege);
            case "PUT" :
                log.debug("method:PUT");
                return hasPrivilege(methodPut.getUrl(), privilege);
            case "DELETE" :
                log.debug("method:DELETE");
                return hasPrivilege(methodDelete.getUrl(), privilege);
            default:
                log.debug("unknow method");
                return false;
        }
    }

    /**
     * 判断权限集合中是否包含指定权限
     * @param privileges 权限集合
     * @param privilege 权限
     * @return boolean
     *
     * @author cx
     * @since 2015-02-28
     */
    private boolean hasPrivilege(final List<String> privileges, final String privilege) {
        if (privileges != null) {
            log.debug("privileges != null");
            return privileges.contains(privilege);
        }

        log.debug("判断权限集合中是否包含指定权限");
        log.warn("权限集合为null");
        return false;
    }
}
